/*
 * 创建日期 2004-9-23
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.ctsi.commons.util.crypto;

import com.ctsi.commons.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * @author Administrator
 * 
 *         更改所生成类型注释的模板为 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class HashCrypt {

	private static final Logger log = LoggerFactory.getLogger(HashCrypt.class);

	public static final String getDigestHash(final String str) {
		return getDigestHash(str, "SHA");
	}

	public static final String getDigestHashWithCharset(final String str, final String code) {
		return getDigestHash(str, code, "SHA");
	}

	public static final String getDigestHash(final byte[] bytes) {
		return getDigestHash(bytes, "SHA");
	}

	public static final String getDigestHash(final byte[] bytes, final String hashType) {

		if (bytes == null)
			return null;
		try {
			MessageDigest messagedigest = MessageDigest.getInstance(hashType);

			messagedigest.update(bytes);
			byte digestBytes[] = messagedigest.digest();
			// char[] digestChars = Hex.encodeHex(digestBytes);

			// return new String(digestChars, 0, digestChars.length);
			return byteToHex(digestBytes);
		} catch (Exception e) {
			log.error("Error while computing hash of type " + hashType);
			throw new RuntimeException(e);
		}

	}

	public static final byte[] getDigestHashByte(final byte[] bytes, final String hashType) {
		if (bytes == null)
			return null;
		try {
			MessageDigest messagedigest = MessageDigest.getInstance(hashType);

			messagedigest.update(bytes);
			return messagedigest.digest();

		} catch (Exception e) {
			log.error("Error while computing hash of type " + hashType);
			throw new RuntimeException(e);
		}
	}

	private static final String byteToHex(final byte[] bytes) {

		return StringUtil.byte2hex(bytes, null);
	}

	public static final String getDigestHash(final String str,final  String hashType) {
		if (str == null)
			return null;
		return getDigestHash(str.getBytes(), hashType);

	}

	public static final String getDigestHash(final String str, final String code,final  String hashType) {
		if (str == null)
			return null;
		try {
			byte codeBytes[] = null;

			if (code == null)
				codeBytes = str.getBytes();
			else
				codeBytes = str.getBytes(code);
			MessageDigest messagedigest = MessageDigest.getInstance(hashType);

			messagedigest.update(codeBytes);
			byte digestBytes[] = messagedigest.digest();
			// char[] digestChars = Hex.encodeHex(digestBytes);;

			// return new String(digestChars, 0, digestChars.length);
			return byteToHex(digestBytes);
		} catch (Exception e) {
			log.error("Error while computing hash of type " + hashType);
			throw new RuntimeException(e);
		}

	}

 
}
